﻿using Itech_Run.Blog.Application.Contracts.Dto;
using Itech_Run.Blog.Application.Contracts.Service;
using Itech_Run.Domain.Shared.Const;
using Itech_Run.HttpApi.Shared.Result;
using Itech_Run.Helper.String;
using Itech_Run.HttpApi.Shared;
using Itech_Run.Sys.Application.Contracts.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Itech_Run.Blog.HttpApi.Controllers
{
    public class Front_BlogInfoController : BaseApiController
    {
        private readonly IFront_BlogInfoService _blogInfoService;
        private readonly ISysUserService _sysUserService;
        public Front_BlogInfoController(IFront_BlogInfoService blogInfoService, ISysUserService sysUserService)
        {
            _blogInfoService = blogInfoService;
            _sysUserService = sysUserService;
        }

        [AllowAnonymous]
        [HttpGet]
        public async Task<CustomResult> GetListAsync([FromQuery] Front_BlogInfoListDto listDto)
        {
            var result = await _blogInfoService.GetListAsync(listDto);
            if (result.Items.Any())
            {
                var userKeyValues = await _sysUserService.GetListAsync(result.Items.Select(s => s.CreatedBy).Distinct().ToArray());
                foreach (var item in result.Items)
                {
                    item.Content = item.Content.HTMLSubstring(BlogConst.DigestLength, "...");
                    item.CreatedByName = userKeyValues.Where(p => p.Key == item.CreatedBy).Select(s => s.Value).SingleOrDefault();
                }
            }
            return new CustomResult(result);
        }

        [AllowAnonymous]
        [HttpGet]
        public async Task<CustomResult> GetAsync(string id)
        {
            var result = await _blogInfoService.GetAsync(id);
            if (result != null)
            {
                var userKeyValues = (await _sysUserService.GetListAsync(result.CreatedBy ?? "")).Distinct().ToArray();
                result.CreatedByName = userKeyValues.Where(p => p.Key == result.CreatedBy).Select(s => s.Value).SingleOrDefault();
            }
            return new CustomResult(result ?? new Front_BlogInfoDto());
        }

        [AllowAnonymous]
        [HttpPost]
        public async Task<CustomResult> AddReadNumAsync(string blogId)
        {
            await _blogInfoService.AddReadNum(blogId);
            return GetSuccesResult();
        }
    }
}
